package com.yuyou.fn.filter;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.Principals;
import com.yuyou.fn.controller.ReturnResult;
import com.yuyou.fn.platform.service.IAccessTokenService;
import com.yuyou.fn.platform.vo.AccessTokenVo;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by wens on 16/8/27.
 */
public class ApiAuthFilter implements Filter {

    private IAccessTokenService accessTokenService ;

    private volatile Map<String,Boolean> excludedUrlsMap = new HashedMap<>() ;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request  = (HttpServletRequest)req ;

        String requestURI = request.getRequestURI();
        //例外
        if(excludedUrlsMap.containsKey(requestURI)){
            chain.doFilter(req,res);
            return ;
        }

        String token = request.getHeader("accessToken");

        if(StringUtils.isEmpty(token)){
            token = request.getParameter("accessToken") ;
        }

        try{
            AccessTokenVo accessToken = accessTokenService.validAccessToken(token);
            request.setAttribute("accessToken",accessToken);
            Principals.Principal principal = new Principals.Principal(accessToken.getUserId(),accessToken.getName());
            Principals.set(principal);
        }catch (BusException e ){
            writeResult((HttpServletResponse)res, ReturnResult.fail(e.getMessage()));
            return ;
        }
        chain.doFilter(req,res);
    }


    public void init(FilterConfig filterConfig) {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
        accessTokenService = webApplicationContext.getBean(IAccessTokenService.class);

        String excludedUrls = filterConfig.getInitParameter("excludedUrls");

        if(excludedUrls != null ){
            String[] urls = excludedUrls.trim().split(",|;");
            String contextPath = filterConfig.getServletContext().getContextPath();
            for(String url : urls ){
                excludedUrlsMap.put(contextPath + url.trim(),Boolean.TRUE );
            }
        }

    }

    public void destroy() {
    }

    private void writeResult(HttpServletResponse response , ReturnResult result ) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(result,true ));
    }
}
